import React, { createContext } from 'react';
import zhCNData from './zh-CN';
import enUSData from './en-US';

export type LocaleData = {
  locale: string,
  [key: string] : string;
};

class LocaleCache {
  localeData: Record<string, Record<string, string>> = {
    'zh-CN': zhCNData,
    'en-US': enUSData
  };
  locale = 'zh-CN';

  constructor() {
    this.setLocaleData(zhCNData);
  }

  setLocale(locale: string) {
    this.locale = locale;
  }

  setLocaleData(localeData: LocaleData) {
    this.locale = localeData.locale;
    this.localeData[localeData.locale] = localeData;
  }

  getLocaleData(locale: string) {
    return this.localeData[locale];
  }

  getLocal() {
    return this.locale;
  }

  existLocale(locale: string) {
    return this.localeData[locale] ? true: false;
  }

  getLocaleTranslation(locale: string, label: string) {
    if(!this.existLocale(locale)) return '-';
    return this.localeData[locale][label] || '-';
  }

  getTranslation(label: string) {
    return this.getLocaleTranslation(this.locale, label);
  }
}

export interface LocaleProviderProps {
  locale: string;
  children?: React.ReactNode;
  T?: Function
}

interface LocaleContextProps extends LocaleProviderProps {
  localeCache: LocaleCache;
  T: Function
}

const localeCache = new LocaleCache();

export const LocaleContext = createContext<LocaleContextProps>({
  localeCache,
  locale: 'zh-CN',
  T: localeCache.getTranslation.bind(localeCache)
});

LocaleContext.displayName = 'LocaleProvider';

/**
 * 语言提供者
 * @param props
 * @constructor
 */
export function LocaleProvider(props: LocaleProviderProps) {
  const { locale, children } = props;

  const localeConfig = React.useMemo(() => {
    localeCache.setLocale(locale);
    return {
      locale,
      localeCache,
      T: props.T || localeCache.getTranslation.bind(localeCache)
    };
  }, [locale]);


  return <LocaleContext.Provider value={localeConfig}>{children}</LocaleContext.Provider>;
}

LocaleProvider.LocaleContext = LocaleContext;




